import PropTypes from '../_util/vue-types';

export default {
  name: 'CInputNumber',
  inheritAttrs: false,
  model: {
    prop: 'value',
    event: 'change.value',
  },
  props: {
    value: PropTypes.oneOfType([Number, String]).def(undefined),
    size: PropTypes.oneOf(['small', 'default', 'large']).def('default'),
    // 整数部分长度限制
    intLimit: PropTypes.number.def(12),
    // 小数部分长度限制
    decLimit: PropTypes.number.def(2),
    // 最大值
    max: PropTypes.oneOfType([String, Number]),

    //最小值
    min: PropTypes.oneOfType([String, Number]),

    disabled: PropTypes.bool.def(false),
    // 是否清除不合法的输入
    resetIllegal: PropTypes.bool.def(false),
  },
  data() {
    return {
      listenersEvents: {},
      cpValue: undefined,
      oldValue: undefined,
      isFocus: false,
      maxNum: null,
      minNum: null,
    };
  },
  watch: {
    max: {
      handler(val) {
        let formatedMax = this.format(val);
        if (formatedMax) {
          this.maxNum = this.lengthLimit(formatedMax);
        }
      },
      immediate: true,
    },
    min: {
      handler(val) {
        let formatedMin = this.format(val);
        if (formatedMin) {
          this.minNum = this.lengthLimit(formatedMin);
        }
      },
      immediate: true,
    },
    value: {
      handler(val) {
        let cleanVal = this.numFactory(val);
        if (this.resetIllegal) {
          // 判断value绑定值是否合法，不合法就清空
          this.cpValue = String(val) === cleanVal ? cleanVal : '';
        } else {
          this.cpValue = cleanVal;
        }
      },
      immediate: true,
    },
  },
  created() {
    this.setListeners();
  },
  methods: {
    setListeners() {
      // eslint-disable-next-line no-unused-vars
      let { input, ...events } = this.$listeners;
      this.listenersEvents = { ...this.listenersEvents, ...events };
    },
    // 整理金额数字规范
    format(val) {
      let reduceNaNReg = /\D+/g; // 去除非数字
      let reduceZeroReg = /^0*(?=[0-9])/; // 去除无意义0

      // 因为有补0操作，当进行删除时判断，如果为空直接返""，不再补0
      if (val || String(val) === '0') {
        let strArr = String(val).split('.');
        // 没有输入整数部分时，补0
        strArr[0] = (strArr[0] || '0').replace(reduceNaNReg, '').replace(reduceZeroReg, '');
        // 判断是否已经输入小数点
        if (strArr[1] !== undefined) {
          strArr[1] = strArr[1].replace(reduceNaNReg, '');
          return strArr[0] + '.' + strArr[1];
        } else {
          return strArr[0];
        }
      } else {
        return '';
      }
    },
    // 限制数字的整数部分和小数部分长度
    lengthLimit(val) {
      if (val) {
        let strArr = String(val).split('.');
        let oldStrArr = this.oldValue ? this.oldValue.split('.') : [''];
        if (this.intLimit !== undefined) {
          if (strArr[0].length > this.intLimit) {
            strArr[0] = oldStrArr[0] || strArr[0].substr(0, this.intLimit);
          } else {
            strArr[0] = strArr[0].substr(0, this.intLimit);
          }
        }
        // 判断是否允许输入小数且已经输入小数点
        if (this.decLimit !== 0 && strArr[1] !== undefined) {
          if (this.decLimit !== undefined) {
            if (strArr[1].length > this.decLimit) {
              strArr[1] = oldStrArr[1] || strArr[1].substr(0, this.decLimit);
            } else {
              strArr[1] = strArr[1].substr(0, this.decLimit);
            }
          }
          return strArr[0] + '.' + strArr[1];
        } else {
          return strArr[0];
        }
      } else {
        return '';
      }
    },
    // 限制数字最大值
    maxLimit(val) {
      if (this.maxNum !== null && val && Number(val) > this.maxNum) {
        return String(this.maxNum);
      }
      return val;
    },
    // 限制数字最小值
    mixLimit(val) {
      if (this.minNum !== null && val && Number(val) < this.minNum) {
        return String(this.minNum);
      }
      return val;
    },
    numFactory(val) {
      return this.minNum !== null && val && Number(val) < this.minNum ? this.mixLimit(this.lengthLimit(this.format(val))): this.maxLimit(this.lengthLimit(this.format(val)));
    },
    // 去除末位的小数点
    reduceSpot(e) {
      e.target.value = e.target.value.replace(/\.$/, '');
      this.handleChangeValue(e);
    },
    handleFocus() {
      this.isFocus = true;
    },
    handleBlur(e) {
      this.reduceSpot(e);
      this.isFocus = false;
    },
    handleChangeValue(e) {
      this.oldValue = this.cpValue;
      let res = this.numFactory(e.target.value);
      e.target.value = res;
      this.$emit('change.value', res);
      this.$emit('input', e);
      // 模拟a-input的change事件是在input触发的
      this.$emit('change', e);
      // 当没有使用value进行绑定时，确保input显示正确
      this.cpValue = this.value === undefined ? res : this.value;
    },
  },
  render(h) {
    let {
      size,
      disabled,
      isFocus,
      cpValue,
      listenersEvents,
      handleFocus,
      handleBlur,
      handleChangeValue,
      $attrs,
      $slots,
    } = this;

    return (
      <div class="c-input-number-wrapper">
        <div
          class={`c-input-number
            ${size === 'large' ? 'c-input-number-lg' : size === 'small' ? 'c-input-number-sm' : ''}
            ${disabled ? 'c-input-number-disabled' : ''}
            ${isFocus ? 'c-input-number-focus' : ''}`}
        >
          {$slots.prefix && <div class="prefix-wrapper">{$slots.prefix}</div>}
          <input
            value={cpValue}
            disabled={disabled}
            type="text"
            onFocus={handleFocus}
            onBlur={handleBlur}
            onInput={handleChangeValue}
            {...{ attrs: $attrs, on: listenersEvents }}
          />
          {$slots.suffix && <div className="suffix-wrapper">{$slots.suffix}</div>}
        </div>
      </div>
    );
  },
};
